package com.bawei.home

import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.common.entity.VideoEntity
import com.bawei.common.mvi.BaseEvent
import com.bawei.common.mvi.BaseMviFragment
import com.bawei.home.adapter.ListVideoAdapter
import com.bawei.home.databinding.FragmentListBinding
import com.bawei.home.dialog.VideoCommendFragment
import com.bawei.home.viewmodel.HomeViewModel
import com.bumptech.glide.Glide
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

private const val ARG_ID = "id"
private const val ARG_CHANNEL_ID = "channelId"

@AndroidEntryPoint
class ListFragment : BaseMviFragment<FragmentListBinding>() {

    private val mViewModel: HomeViewModel by activityViewModels()
    private var videoList = mutableListOf<VideoEntity>()
    private var id: Int = -1
    private var channelId: String = ""
    private var pageIndex = 1
    private var pageSize = 10
    private lateinit var mAdapter: ListVideoAdapter
    private lateinit var mRecyclerView: RecyclerView

    companion object {
        @JvmStatic
        fun newInstance(id: Int, channelId: String) =
            ListFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_ID, id)
                    putString(ARG_CHANNEL_ID, channelId)
                }
            }
    }

    override fun getLayoutId(): Int = R.layout.fragment_list

    override fun initViews() {
        //获取传递进来参数
        arguments?.let {
            id = it.getInt(ARG_ID)
            channelId = it.getString(ARG_CHANNEL_ID).toString()
        }

        //下拉刷新事件
        mDataBinding.refreshLayout.setOnRefreshListener { //页面参数
            pageIndex = 1
            //重新发送请求意图
            refreshOrMoreList()
        }

        //初始化RecyclerView
        mRecyclerView = mDataBinding.rvHomeList
        //默认ItemView缓存大小为2, 数值越大缓存的Item就越多，占用内存就越大
        mRecyclerView.setItemViewCacheSize(10)
        mRecyclerView.setHasFixedSize(true) //Item布局大小为固定大小

        //适当调整缓存池大小, 默认缓存池的大小为5
        var pool = RecyclerView.RecycledViewPool()
        pool.setMaxRecycledViews(0, 5)
        mRecyclerView.setRecycledViewPool(pool)

        //根据RecyclerView的滚动事件来暂停或恢复加载
        mRecyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(this@ListFragment).resumeRequests() //恢复图片加载
                } else {
                    Glide.with(this@ListFragment).pauseRequests() //暂停图片加载
                }
            }
        })

        //取消不需要的Item动画
        (mRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        //为layoutManager预留更多空间

        mRecyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)

        mAdapter = ListVideoAdapter(videoList).apply {
            preloadItemCount = 4
            onPreload = {
                pageIndex += 1
                refreshOrMoreList()
            }
        }
        //点击事件
        mAdapter.setOnItemClickListener(object:ListVideoAdapter.OnItemClickListener{
            override fun onItemChildClick(v: View?, position: Int) {
                when(v?.id){
                    R.id.iv_video_play -> itemVideoPlay(position)
                    R.id.iv_commend -> itemCommendView(position)
                    R.id.iv_more -> itemMoreView(position)
                }
            }
        })
        //设置数据适配器对象
        mRecyclerView.swapAdapter(mAdapter, true)

    }

    /**
     * 查看更多内容
     */
    private fun itemMoreView(position: Int) {
        val entity = videoList[position]
        EventBus.getDefault().post(BaseEvent("MainActivity", entity, 101))
    }

    /**
     * 查看视频评论
     */
    private fun itemCommendView(position: Int) {
        val entity = videoList[position]

        //方式一：从当前的Activity获取FragmentManager
        val fragment = VideoCommendFragment(entity.item_id)
        activity?.supportFragmentManager?.let {
            fragment.show(it, "videoCommend")
        }

        //方式二：发送事件到Activity中执行
//        val entity = videoList[position]
//        EventBus.getDefault().post(BaseEvent("MainActivity", entity, 100))
    }

    /**
     * 播放视频
     */
    private fun itemVideoPlay(position: Int) {
        val entity = videoList[position]
        ARouter.getInstance().build("/video/play")
            .withSerializable("videoEntity", entity)
            .withInt("typeId", id)
            .withString("channelId", channelId)
            .navigation()
    }

    override suspend fun sendViewIntent() {
        //推荐
        if(id == -1){
            mViewModel.channel.send(HomeViewIntent.LoadRecommendSimpleVideo(pageIndex, pageSize))
        }
        //分类
        else {
            mViewModel.channel.send(HomeViewIntent.LoadSimpleVideoByChannelId(channelId, pageIndex, pageSize))
        }
    }

    override suspend fun collectUIState() {
        mViewModel.uiState.collect{
            when(it){
                is HomeUiState.LoadSimpleVideoSuccess -> {
                    //结束刷新和加载更多
                    mDataBinding.refreshLayout.finishRefresh()
                    if(pageIndex == 1){
                        videoList.clear()
                    }
                    videoList.addAll(it.list)
                    //更新Adapter
                    mAdapter.notifyDataSetChanged()
                }
                is HomeUiState.LoadSimpleVideoFail -> {
                    showToastMessage(it.msg)
                    //重置页面ID, 防止页数不断增加
                    if (pageIndex > 1) {
                        pageIndex -= 1
                    }
                }
                else -> {}
            }
        }

    }

    private fun refreshOrMoreList(){
        lifecycleScope.launch {
            //推荐
            if(id == -1){
                mViewModel.channel.send(HomeViewIntent.LoadRecommendSimpleVideo(pageIndex, pageSize))
            }
            //分类
            else {
                mViewModel.channel.send(HomeViewIntent.LoadSimpleVideoByChannelId(channelId, pageIndex, pageSize))
            }
        }
    }



}